﻿/**
 * ByteArrayCodec
 *
 * @author		Allen Chou
 * @version		1.0.0 (last update: Nov 24 2008)
 * @link        http://cjcat.blogspot.com
 * @link		http://cjcat2266.deviantart.com
 */

package idv.cjcat.utils {
	import flash.utils.ByteArray;

	/**
	 * The <code>ByteArrayCodec</code> class lets you perform conversions between byte arrays and strings.
	 * <p>
	 * The main purpose of encoding a byte array into a string is to allow users to wrap a byte array dada into AS files.
	 * </p>
	 * <p>
	 * One of the main usages of this class is to embed a PBJ (Pixel Bender filter byte array file) file into an AS file.
	 * To obtain a string converted from a PBJ file's byte array, you'll need the PBJ String Generator, which can be obtained on the library homepage.
	 * </p>
	 */
	public class ByteArrayCodec {
		
		public static function encode(ba:ByteArray):String {
			var result:String = "";
			var buffer:String;
			var temp:int;
			var size:uint = ba.bytesAvailable;
			for (var i:uint = 0; i < size; i++) {
				temp = ba.readByte();
				temp += 0x80;
				buffer = temp.toString(16);
				if (buffer.length == 1) buffer = "0" + buffer;
				result += buffer;
			}
			result = result.toUpperCase();
			
			return result;
		}
		
		public static function decode(str:String):ByteArray {
		var temp:String = "";
			var ba:ByteArray = new ByteArray();
			for (var i:uint = 0; i < str.length / 2; i++) {
				temp = str.substr(i * 2, 2);
				ba.writeByte(parseInt(temp, 16) - 0x80);
			}
			
			return ba;
		}
		
	}
}